from .Object import PlyEdge, PlyVertex, PlyFace, PlyModel
from . import Tool
import time


def optimizeFaceList(queue, faceList:list, tid, switchMode=False, allValue=0):
    time1 = time.time()
    newFaceList = []
    putMessage(queue,'预处理',tid)
    predDict = Tool.preteatmentFaces(faceList, switchMode)
    i, l =0, len(predDict)
    for k in predDict:
        i += 1
        a = len(predDict[k])
        opedFaceList = Tool.optimizeFaces(predDict[k], switchMode)
        msg = f'{i}/{l}: {a} -> {len(opedFaceList)}'
        putMessage(queue, msg, tid)
        newFaceList.extend(opedFaceList)
        time2 = time.time()
        if time2 - time1 > 0.1:
            pubProgressValue(queue, i/l, allValue, tid)
    pubProgressValue(queue, 1, allValue, tid)
    return newFaceList

def optimizeModel(queue, model:PlyModel,optimVer=True, switchMode=False, tid='newThread'):
    '''优化模型'''
    putMessage(queue, '开始优化',tid)
    faceList = model.faceList.copy()
    allValue, selfadd = 0, 0.33
    if not optimVer:
        selfadd = 0.5
    # 创建一个用于存放已经合并的面的list
    putMessage(queue,'modeA', tid)
    newFaceList = optimizeFaceList(queue,faceList, switchMode=switchMode, tid=tid, allValue=allValue)
    putMessage(queue,'modeB', tid)
    allValue += selfadd
    newFaceList = optimizeFaceList(queue,newFaceList, switchMode=(not switchMode), tid=tid, allValue=allValue)
    if optimVer:
        putMessage(queue,'顶点优化中',tid)
        allValue += selfadd
        newFaceList = Tool.optimizeVertexes(newFaceList)
        putMessage(queue,'顶点优化完成',tid)
    newModel = PlyModel(newFaceList)
    pubProgressValue(queue, 1, 1, tid)
    putModel(queue,newModel,tid)

def load(queue, filepath,tid='newThread'):
    '''打开filepath文件并put到queue中
    queue中的内容包括一些
    '''
    putMessage(queue,'开始读取文件', tid)
    file = open(filepath, 'r')
    fileContent = [i[0:-1] for i in file.readlines()]
    file.close()
    putMessage(queue,'读取完成，开始处理数据', tid)
    # 从读取到的Content中获取顶点数和面数
    verNum, faceNum = -1,-1
    verStart = -1
    for i in range(len(fileContent)):
        s = fileContent[i]
        if 'element vertex' in s:
            verNum = int(s.split(' ')[-1])
        elif 'element face' in s:
            faceNum = int(s.split(' ')[-1])
        elif 'end_header' in s:
            verStart = i+1
            break
    putMessage(queue,'数据分割完成', tid)
    # 根据得到的数据分解顶点列表和面列表
    verEnd = verStart + verNum
    venewObjListist = []
    for s in fileContent[verStart: verEnd]:
        t = s.split(' ') # [x, y, z, ……]
        venewObjListist.append(PlyVertex(t[0], t[1], t[2]))
    putMessage(queue, '顶点处理完成', tid)
    faceStart = verEnd
    faceEnd = faceStart + faceNum
    faceList = []
    for s in fileContent[faceStart : faceEnd]:
        t = s.split(' ')[1:]
        vl = [venewObjListist[int(vid)] for vid in t]
        faceList.append(PlyFace(vl))
    putMessage(queue, '面片处理完成', tid)
    model = PlyModel(faceList)
    putModel(queue, model, tid)
    putMessage(queue,'模型构建完成', tid)

def putModel(queue,content, tid=''):
    msg = {'id':tid, 'type':'model', 'content':content}
    queue.put(msg)

def putMessage(queue, content, tid=''):
    msg = {'id':tid, 'type':'msg', 'content':content}
    queue.put(msg)

def pubProgressValue(queue, value, allValue,tid='',):
    msg = {'id':tid, 'type':'progress', 'content':{'value':value, 'allValue':allValue}}
    queue.put(msg)

